import logging
import os
import getpass
from lib import constants as C

mypid = str(os.getpid())
user = getpass.getuser()
logger = logging.getLogger("p=%s u=%s | " % (mypid, user))
logger.setLevel(logging.DEBUG)
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.INFO)
fileHandler1 = logging.FileHandler(C.LOG_INFO_FILE, mode='a', encoding='utf-8')
fileHandler1.setLevel(logging.INFO)
fileHandler2 = logging.FileHandler(C.LOG_ERROR_FILE, mode='a', encoding='utf-8')
fileHandler2.setLevel(logging.ERROR)
fileHandler3 = logging.FileHandler(C.LOG_ERROR_FILE, mode='a', encoding='utf-8')
fileHandler3.setLevel(logging.WARNING)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
consoleHandler.setFormatter(formatter)
fileHandler1.setFormatter(formatter)
fileHandler2.setFormatter(formatter)
fileHandler3.setFormatter(formatter)


class Display(object):
    def __init__(self, log_info_file=C.LOG_INFO_FILE, log_error_file=C.LOG_ERROR_FILE):
        self.log_info_file = log_info_file
        self.log_error_file = log_error_file

    def display(self, msg, screen_only=False, log_only=False, error=False, level='info'):
        if logger.handlers:
            logger.handlers = []

        if screen_only:
            logger.addHandler(consoleHandler)
            if level == 'info':
                logger.info(msg)
            elif level == 'warning':
                logger.warning(msg)
            pass

        if log_only:
            logger.addHandler(fileHandler1)
            if error:
                logger.addHandler(fileHandler2)
                logger.error(msg)
            else:
                if level == 'info':
                    logger.info(msg)
                elif level == 'warning':
                    logger.warning(msg)
            pass

        if not screen_only and not log_only:
            logger.addHandler(consoleHandler)
            logger.addHandler(fileHandler1)

            if error:
                logger.addHandler(consoleHandler)
                logger.addHandler(fileHandler1)
                logger.addHandler(fileHandler2)
                logger.error(msg)
            else:
                logger.addHandler(fileHandler1)
                if level == 'info':
                    logger.info(msg)
                elif level == 'warning':
                    logger.warning(msg)

    def info(self, msg):
        self.display(msg)

    def warning(self, msg):
        self.display(msg, level='warning')

    def error(self, msg):
        self.display(msg, error=True)

    def screen_only(self, msg):
        self.display(msg, screen_only=True, log_only=False, error=False)

    def log_only(self, msg):
        self.display(msg, screen_only=False, log_only=True, error=False)
